/**
 * bus事件通讯封装
 * 主要用于单向事件交互，并且自动在组件销毁前把事件解绑
 * 如果需要双向或复杂数据驱动，建议用vuex，但vuex始终占用内存，不适合存大数据（如api返回结果）
 */
import EventBus from '@/event-bus/EventBus.js';

export default {
  emits: [],
  props: {
    widgetInstanceId: {
      type: String,
      default: '',
    },
  },

  data() {
    return {
      vmEvents: [],
    };
  },

  beforeUnmount() {
    this.vmEvents.forEach(evtKey => {
      EventBus.$off(evtKey);
    });
  },

  methods: {
    $busEmit(evtKey, value, addWid = false) {
      let _evtKey = evtKey;
      if (addWid) {
        _evtKey = `${evtKey}_${this.widgetInstanceId}`;
      }
      EventBus.$emit(_evtKey, value);
    },

    $busOn(evtKey, callback, addWid = false) {
      let _evtKey = evtKey;
      if (addWid) {
        _evtKey = `${evtKey}_${this.widgetInstanceId}`;
      }
      if (!this.vmEvents.includes(_evtKey)) {
        this.vmEvents.push(_evtKey);
      }
      EventBus.$on(_evtKey, value => callback(value));
    },

    $busOnce(evtKey, callback, addWid = false) {
      let _evtKey = evtKey;
      if (addWid) {
        _evtKey = `${evtKey}_${this.widgetInstanceId}`;
      }
      if (!this.vmEvents.includes(_evtKey)) {
        this.vmEvents.push(_evtKey);
      }
      EventBus.$once(_evtKey, value => callback(value));
    },

    // 本地环境生效
    $busOnLocal(evtKey, callback, addWid = false) {
      if (window.isLocalEnv) {
        this.$busOn(evtKey, callback, addWid);
      }
    },

    // 本地环境生效
    $busOnceLocal(evtKey, callback, addWid = false) {
      if (window.isLocalEnv) {
        this.$busOnce(evtKey, callback, addWid);
      }
    },
  },
};
